package com.ruoyi.web.controller.gym;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/gym/image")
public class GymDownImgController extends BaseController {

    /**
     * 根据图片路径获取图片
     *
     * @param imagePath 图片路径
     * @param response HTTP响应对象
     * @return 处理结果
     */
    @GetMapping("/download")
    public AjaxResult getImage(@RequestParam("imagePath") String imagePath, HttpServletResponse response) {
        try {
            // 创建文件对象
            File file = new File(imagePath);
            
            // 检查文件是否存在
            if (!file.exists()) {
                return AjaxResult.error("图片不存在");
            }

            // 设置响应类型
            response.setContentType("image/jpeg");
            // 设置响应头
            response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
            
            // 读取文件并写入响应流
            try (FileInputStream fis = new FileInputStream(file);
                 OutputStream os = response.getOutputStream()) {
                
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    os.write(buffer, 0, length);
                }
                os.flush();
                return AjaxResult.success();
            }
        } catch (IOException e) {
            return AjaxResult.error("图片下载失败：" + e.getMessage());
        }
    }
}